import { Component, OnInit ,Inject ,Input} from '@angular/core';
import { MySelection } from 'app/modules/base/selection';
import { map, tap } from 'rxjs/operators';
import { ListResult, ListOption, APIBase, ArrayAPIBase } from 'app/modules/base/api-base'
import { HttpClient } from '@angular/common/http';
import { MatDialogRef ,MAT_DIALOG_DATA} from '@angular/material';
import { ToasterService } from 'app/modules/share/services/toaster.service';

@Component({
  selector: 'm-add-modal',
  templateUrl: './add-modal.component.html',
  styleUrls: ['./add-modal.component.scss']
})
export class AddModalComponent implements OnInit {
  selection = new MySelection<any>('id');
  dataSource: APIBase<any, any>;
  defaultOption = {filter_ids:''};
  selectedService$ = this.selection.change.pipe(
    map(() => {
      const datasource = new ArrayAPIBase(this.selection.selected);
      datasource.search = (obj: any, keyword: string) => {
        keyword.toLowerCase();
        if (obj.name && obj.name.toLowerCase().includes(keyword.toLowerCase())) {
          return true;
        }
        if (obj.full_name && obj.full_name.toLowerCase().includes(keyword.toLowerCase())) {
          return true;
        }
        if (obj.job_number && obj.job_number.toLowerCase().includes(keyword.toLowerCase())) {
          return true;
        }
        return false;
      };
      return datasource;
    }),
  );
  constructor(
    private http: HttpClient , 
    private dialog: MatDialogRef<any>,
    private toaster: ToasterService,
    @Inject(MAT_DIALOG_DATA) private data: {select:[]}
    
    ) { }
  
  ngOnInit() {
    let selectIds = this.data.select.map((item:any)=> item.id)
    this.defaultOption.filter_ids = selectIds.join(',');
    this.dataSource = new APIBase<any, any>(this.http, `api/admin/pc`);
  }
  cancel() {
   this.dialog.close();
  }
  async save() {
    if(this.selection.selected.length==0 && location.pathname.startsWith('/task/add')){
      this.toaster.warn('no pc_id');
      // window['$angularToast'].t.error('no pc_id');
      // return false;
    }
    this.dialog.close(this.selection.selected);
  }
}
